#!/usr/bin/python3.6  
# -*- coding: utf-8 -*- 

import pickle
import gzip
import theano
import theano.tensor as T
import numpy


class Mnist:

    def shared_dataset(self, data_xy):
        """ Function that loads the dataset into shared variables
    
        The reason we store our dataset in shared variables is to allow
        Theano to copy it into the GPU memory (when code is run on GPU).
        Since copying data into the GPU is slow, copying a minibatch everytime
        is needed (the default behaviour if the data is not in a shared
        variable) would lead to a large decrease in performance.
        """
        data_x, data_y = data_xy
        shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX))
        shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX))
        # When storing data on the GPU it has to be stored as floats
        # therefore we will store the labels as ``floatX`` as well
        # (``shared_y`` does exactly that). But during our computations
        # we need them as ints (we use labels as index, and if they are
        # floats it doesn't make sense) therefore instead of returning
        # ``shared_y`` we will have to cast it to int. This little hack
        # lets us get around this issue
        return shared_x, T.cast(shared_y, 'int32')

    def __init__(self, data_file):
        """data_file,namely mnist.pkl.gz,is a pickled dataset of mnist.The pickled file 
        represents a tuple of 3 lists : the training set, the validation set and the 
        testing set. Each of the three lists is a pair formed from a list of images and 
        a list of class labels for each of the images. An image is represented as 
        numpy 1-dimensional array of 784 (28 x 28) float values between 0 and 1 
        (0 stands for black, 1 for white). The labels are numbers between 0 and 9 indicating 
        which digit the image represents. The code block below shows how to load the dataset.
        
        """
        self.data_file = data_file
        # Load the dataset
        with gzip.open(self.data_file, 'rb') as f:
            self.train_set, self.valid_set, self.test_set = pickle.load(f, encoding='bytes')
    
        self.valid_set_x, self.valid_set_y = self.shared_dataset(self.valid_set)
        self.train_set_x, self.train_set_y = self.shared_dataset(self.train_set)
        self.test_set_x, self.test_set_y = self.shared_dataset(self.test_set)

            
if __name__ == '__main__':
    m = Mnist('data\\mnist.pkl.gz')
    print('Training data number:%d' % len(m.train_set[0]))
    print('Testing data number:%d' % len(m.test_set[0]))
    print('Validating data number:%d' % len(m.valid_set[0]))
    
